package xzit.gcxy.xxhzx.zhh.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.criterion.DetachedCriteria;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import xzit.gcxy.xxhzx.zhh.client.Client;
import xzit.gcxy.xxhzx.zhh.common.AjaxJson;
import xzit.gcxy.xxhzx.zhh.common.Pagination;
import xzit.gcxy.xxhzx.zhh.common.ResourceUtil;
import xzit.gcxy.xxhzx.zhh.entity.ManagedAccountVO;
import xzit.gcxy.xxhzx.zhh.entity.TeacherInfoVO;
import xzit.gcxy.xxhzx.zhh.entity.TeacherInfoVO4ajax;
import xzit.gcxy.xxhzx.zhh.service.TeacherService;

@Controller
@RequestMapping("/teacherController")
public class TeacherController {

	private static final Logger logger = Logger.getLogger(TeacherController.class);

	@Autowired
	private TeacherService teacherService;

	/**
	 * 初始访问
	 * 
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "goTeacher")
	public ModelAndView goScore(HttpServletRequest request) {
		return new ModelAndView("app/teacher");
	}

	@RequestMapping(params="save")
    @ResponseBody
	public AjaxJson save(HttpServletRequest request, HttpServletResponse response, TeacherInfoVO4ajax teacherEntity) throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("保存成功！");
		j.setSuccess(true);
		try{
			TeacherInfoVO teachervo = new TeacherInfoVO();
			BeanUtils.copyProperties(teachervo, teacherEntity);
			Client client = ResourceUtil.getClient();
			ManagedAccountVO user = client.getUser();
			teachervo.setInstitute(user.getInstitute());
			this.teacherService.save(teachervo);
		}catch(Exception e){
			j.setMsg("保存失败！");
			j.setSuccess(false);
		}
		 return j;
		
	}
	
	@RequestMapping(params="update")
    @ResponseBody
	public AjaxJson update(HttpServletRequest request, HttpServletResponse response, TeacherInfoVO4ajax teacherEntity) throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("更新成功！");
		j.setSuccess(true);
		try{
			TeacherInfoVO teachervo = new TeacherInfoVO();
			BeanUtils.copyProperties(teachervo, teacherEntity);
			Client client = ResourceUtil.getClient();
			ManagedAccountVO user = client.getUser();
			teachervo.setInstitute(user.getInstitute());
			this.teacherService.update(teachervo);
		}catch(Exception e){
			j.setMsg("更新失败！");
			j.setSuccess(false);
		}
		 return j;
		
	}
	
	@RequestMapping(params="delete",method=RequestMethod.POST)
    @ResponseBody
	public AjaxJson delete(HttpServletRequest request, HttpServletResponse response, String ids) throws Exception {
		AjaxJson j = new AjaxJson();
		j.setMsg("删除成功！");
		j.setSuccess(true);
		try{
			for(String id:ids.split(",")){
				TeacherInfoVO teacherEntity = new TeacherInfoVO();
				teacherEntity = teacherService.get(TeacherInfoVO.class, Integer.parseInt(id));
				this.teacherService.delete(teacherEntity);
			}
		}catch(Exception e){
			j.setMsg("删除失败！");
			j.setSuccess(false);
		}
		 return j;
		
	}
	
	@RequestMapping(params = "uploadScore", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson uploadScore(@RequestParam("teacherExcel") MultipartFile teacherExcel) {
		AjaxJson j = new AjaxJson();
		j.setMsg("导入成功！");
		j.setSuccess(true);
		Client client = ResourceUtil.getClient();
		ManagedAccountVO user = client.getUser();
		try {
			if (!teacherExcel.isEmpty()) {
				InputStream is = teacherExcel.getInputStream();
				String[] fileName = teacherExcel.getOriginalFilename().split("\\.");
				List<TeacherInfoVO> teacherList = new ArrayList<TeacherInfoVO>();
				// 判断excel版本
				if ("xls".equals(fileName[1])) {
					HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
					for (int i = 0; i < hssfWorkbook.getNumberOfSheets(); i++) {
						HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i);
						if (hssfSheet == null) {
							continue;
						}
						// 循环行Row
						for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
							HSSFRow hssfRow = hssfSheet.getRow(rowNum);
							if (hssfRow != null) {
								TeacherInfoVO tivo = new TeacherInfoVO();
								HSSFCell gonghao = hssfRow.getCell(0);
								HSSFCell realname = hssfRow.getCell(1);
								HSSFCell telphone = hssfRow.getCell(2);
								HSSFCell business = hssfRow.getCell(3);
								HSSFCell other = hssfRow.getCell(4);
								
								tivo.setGonghao(gonghao.getStringCellValue());
								tivo.setRealname(realname.getStringCellValue());
								tivo.setTelphone(telphone.getStringCellValue());
								tivo.setBusiness(business.getStringCellValue());
								tivo.setOther(other.getStringCellValue());
								tivo.setInstitute(user.getInstitute());
								teacherList.add(tivo);
							}
						}
					}
				} else if ("xlsx".equals(fileName[1])) {
					XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
					for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
						XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
						// Read the Row
						for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
							XSSFRow xssfRow = xssfSheet.getRow(rowNum);
							if (xssfRow != null) {
								TeacherInfoVO tivo = new TeacherInfoVO();
								xssfRow.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
								xssfRow.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
								xssfRow.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
								xssfRow.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
								xssfRow.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
								XSSFCell gonghao = xssfRow.getCell(0);
								XSSFCell realname = xssfRow.getCell(1);
								XSSFCell telphone = xssfRow.getCell(2);
								XSSFCell business = xssfRow.getCell(3);
								XSSFCell other = xssfRow.getCell(4);
								
								tivo.setGonghao(gonghao.getStringCellValue());
								tivo.setRealname(realname.getStringCellValue());
								tivo.setTelphone(telphone.getStringCellValue());
								tivo.setBusiness(business.getStringCellValue());
								tivo.setOther(other.getStringCellValue());
								tivo.setInstitute(user.getInstitute());
								teacherList.add(tivo);
							}
						}
					}
				}else{
					j.setMsg("请导入正确的excel文件！");
					j.setSuccess(false);
				}

				teacherService.saveBatch(teacherList);
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg("导入失败！");
			j.setSuccess(false);
		}
		return j;

	}
	
	@RequestMapping(params = "datagrid")
	@ResponseBody
	public void datagrid(HttpServletRequest request, HttpServletResponse response, TeacherInfoVO ve, String name,
			String teachername, String coursename, String term) throws Exception {
		String page = request.getParameter("page");//easyui datagrid 分页 页号
		String rows = request.getParameter("rows");//easyui datagrid 分页 页数
		if(page == null){
			page = "0";
		}
		if(rows == null){
			rows = "0";
		}
		DetachedCriteria condition = DetachedCriteria.forClass(TeacherInfoVO.class);
		Pagination<?> pagination = teacherService.findPageData(condition,ve,Integer.parseInt(page), Integer.parseInt(rows));
		
		JSONObject jobj = new JSONObject();
		jobj.put("total", pagination.getTotalCount());
		jobj.put("rows", pagination.getDatas());

        response.setCharacterEncoding("utf-8");  
        response.getWriter().write(jobj.toString());

	}
}
